import cv2 as cv
import numpy as np
import copy
videofilename = r'D:\photo\vtest.avi'
video = cv.VideoCapture(videofilename)
fgbg = cv.createBackgroundSubtractorMOG2(detectShadows=True)
thresh = 200
color = np.random.randint(0,255,(255,3))

while True:
    ret,frame = video.read()
    if not ret:
        break

    fgmask = fgbg.apply(frame)
    kernel = np.ones((3,3),np.uint8)
    fgmask = cv.morphologyEx(fgmask,cv.MORPH_OPEN,kernel)
    _,fgmask = cv.threshold(fgmask,50,250,cv.THRESH_BINARY)
    bgimg = fgbg.getBackgroundImage()

    fgmask1 = copy.deepcopy(fgmask)
    contours,_ = cv.findContours(fgmask1,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    count = 0
    for c in contours:
        area = cv.contourArea(c)
        x,y,w,h = cv.boundingRect(c)
        if area < thresh:
            continue
        count+=1
        for i in range(1,count,1):
            cv.rectangle(frame, (x, y), (x + w, y + h),color[i].tolist(), 2)
            cv.putText(frame, str(count), (x, y), cv.FONT_HERSHEY_COMPLEX, 1, color[i].tolist(), 2)
        print('共计目标:',count,'面积:',area,'x:',x,'y:',y)
        cv.imshow("qianjing",fgmask1)
        cv.imshow("vtest",frame)
    key = cv.waitKey(30)
    if key == 27:
        break
video.release()
cv.destroyAllWindows()

# another way
'''import cv2 as cv
import numpy as np
import copy
videofilename = r'D:\photo\vtest.avi'
video = cv.VideoCapture(videofilename)
fgbg = cv.createBackgroundSubtractorMOG2(detectShadows=True)
thresh = 200
color = np.random.randint(0,255,(255,3))

while True:
    ret,frame = video.read()
    mask = np.zeros_like(frame)
    if not ret:
        break

    fgmask = fgbg.apply(frame)
    kernel = np.ones((3,3),np.uint8)
    fgmask = cv.morphologyEx(fgmask,cv.MORPH_OPEN,kernel)
    _,fgmask = cv.threshold(fgmask,50,250,cv.THRESH_BINARY)
    bgimg = fgbg.getBackgroundImage()

    fgmask1 = copy.deepcopy(fgmask)
    contours,_ = cv.findContours(fgmask1,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    count = 0
    for c in contours:
        area = cv.contourArea(c)
        x,y,w,h = cv.boundingRect(c)
        if area < thresh:
            continue
        count+=1
        for i in range(1,count,1):
            mask = cv.rectangle(mask, (x, y), (x + w, y + h),color[i].tolist(), 2)
            frame = cv.putText(frame, str(count), (x, y), cv.FONT_HERSHEY_COMPLEX, 1, color[i].tolist(), 2)
        img = cv.add(mask, frame)
        print('共计目标:',count,'面积:',area,'x:',x,'y:',y)
        cv.imshow("qianjing",fgmask1)
        cv.imshow("vtest",img)
    key = cv.waitKey(30)
    if key == 27:
        break
video.release()
cv.destroyAllWindows()
'''